<template>
  <div class="recycle-container">
    <Header title="回收站" show-back>
      <template #right>
        <van-icon
          v-if="recycleList.length > 0"
          name="delete-o"
          @click="handleClearAll"
        />
      </template>
    </Header>

    <div class="recycle-content">
      <!-- 提示信息 -->
      <div v-if="recycleList.length > 0" class="tip-banner">
        <van-notice-bar
          color="#ff976a"
          background="#fff7cc"
          left-icon="info-o"
        >
          文件在回收站保留30天后将永久删除
        </van-notice-bar>
      </div>

      <!-- 文件列表 -->
      <div class="file-list">
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <van-list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <div
              v-for="file in recycleList"
              :key="file.id"
              class="file-item"
              @click="showFileActions(file)"
            >
              <div class="file-icon">
                <van-icon
                  :name="getFileIcon(file)"
                  :color="getFileIconColor(file)"
                  size="24"
                />
              </div>

              <div class="file-info">
                <div class="file-name">{{ file.fileName }}</div>
                <div class="file-meta">
                  <span v-if="!file.isFolder && file.fileSize">{{ formatFileSize(file.fileSize) }}</span>
                  <span>删除于 {{ formatTime(file.updateTime) }}</span>
                </div>
                <div class="file-path">
                  <van-icon name="location-o" size="12" />
                  原位置：{{ file.parentPath || '根目录' }}
                </div>
              </div>

              <div class="file-actions">
                <van-button
                  size="mini"
                  type="primary"
                  @click.stop="restoreFile(file)"
                >
                  恢复
                </van-button>
                <van-button
                  size="mini"
                  type="danger"
                  @click.stop="deleteForever(file)"
                >
                  删除
                </van-button>
              </div>
            </div>

            <!-- 空状态 -->
            <van-empty
              v-if="recycleList.length === 0 && !loading"
              description="回收站为空"
              image="delete-o"
            >
              <template #description>
                <div class="empty-desc">
                  <p>回收站为空</p>
                  <p>删除的文件会在这里保留30天</p>
                </div>
              </template>
            </van-empty>
          </van-list>
        </van-pull-refresh>
      </div>
    </div>

    <!-- 文件操作面板 -->
    <van-action-sheet
      v-model:show="showActionSheet"
      :actions="fileActions"
      @select="handleFileAction"
      cancel-text="取消"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { showToast, showConfirmDialog } from 'vant'
import Header from '@/components/Header.vue'
import { useRecycleStore } from '@/stores/recycle'
import type { FileInfo } from '@/api/file'

const recycleStore = useRecycleStore()

const {
  recycleList,
  loading,
  fetchRecycleList,
  restoreFileItem,
  deleteFileForever,
  clearAll,
  formatFileSize,
  formatTime
} = recycleStore

// 状态
const refreshing = ref(false)
const finished = ref(false)
const showActionSheet = ref(false)
const selectedFile = ref<FileInfo | null>(null)

// 文件操作选项
const fileActions = [
  { name: '恢复文件', value: 'restore', color: '#1989fa' },
  { name: '彻底删除', value: 'delete', color: '#ee0a24' }
]

// 方法
const onRefresh = async () => {
  refreshing.value = true
  try {
    await fetchRecycleList()
  } finally {
    refreshing.value = false
  }
}

const onLoad = async () => {
  // 这里可以实现分页加载
  finished.value = true
}

const showFileActions = (file: FileInfo) => {
  selectedFile.value = file
  showActionSheet.value = true
}

const handleFileAction = (action: any) => {
  showActionSheet.value = false

  if (!selectedFile.value) return

  switch (action.value) {
    case 'restore':
      restoreFile(selectedFile.value)
      break
    case 'delete':
      deleteForever(selectedFile.value)
      break
  }
}

const restoreFile = async (file: FileInfo) => {
  const confirmed = await showConfirmDialog({
    title: '确认恢复',
    message: `确定要恢复 "${file.fileName}" 吗？`
  })

  if (confirmed) {
    try {
      await restoreFileItem(file.id)
    } catch (error) {
      showToast({
        type: 'fail',
        message: '恢复失败'
      })
    }
  }
}

const deleteForever = async (file: FileInfo) => {
  const confirmed = await showConfirmDialog({
    title: '确认彻底删除',
    message: `确定要彻底删除 "${file.fileName}" 吗？此操作不可恢复！`,
    confirmButtonText: '彻底删除',
    confirmButtonColor: '#ee0a24'
  })

  if (confirmed) {
    try {
      await deleteFileForever(file.id)
    } catch (error) {
      showToast({
        type: 'fail',
        message: '删除失败'
      })
    }
  }
}

const handleClearAll = async () => {
  const confirmed = await showConfirmDialog({
    title: '确认清空回收站',
    message: '确定要清空回收站吗？此操作将彻底删除所有文件，不可恢复！',
    confirmButtonText: '清空回收站',
    confirmButtonColor: '#ee0a24'
  })

  if (confirmed) {
    try {
      await clearAll()
    } catch (error) {
      showToast({
        type: 'fail',
        message: '清空失败'
      })
    }
  }
}

const getFileIcon = (file: FileInfo) => {
  if (file.isFolder === 1) {
    return 'folder-o'
  }

  const ext = file.fileName.split('.').pop()?.toLowerCase()
  switch (ext) {
    case 'jpg':
    case 'jpeg':
    case 'png':
    case 'gif':
    case 'bmp':
    case 'webp':
      return 'photo-o'
    case 'mp4':
    case 'avi':
    case 'mov':
    case 'wmv':
    case 'flv':
      return 'video-o'
    case 'mp3':
    case 'wav':
    case 'aac':
    case 'flac':
      return 'music-o'
    case 'pdf':
      return 'description'
    case 'doc':
    case 'docx':
      return 'description'
    case 'xls':
    case 'xlsx':
      return 'description'
    case 'ppt':
    case 'pptx':
      return 'description'
    case 'txt':
      return 'notes-o'
    case 'zip':
    case 'rar':
    case '7z':
      return 'bag-o'
    default:
      return 'description'
  }
}

const getFileIconColor = (file: FileInfo) => {
  // 回收站中的文件图标都使用灰色调
  return '#969799'
}

onMounted(() => {
  fetchRecycleList()
})
</script>

<style scoped>
.recycle-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f8f8f8;
}

.recycle-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.tip-banner {
  padding: 12px 16px 0;
}

.file-list {
  flex: 1;
  margin: 16px;
  background: white;
  border-radius: 12px;
  overflow: hidden;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
  transition: background-color 0.2s;
}

.file-item:active {
  background-color: #f8f8f8;
}

.file-item:last-child {
  border-bottom: none;
}

.file-icon {
  margin-right: 12px;
  flex-shrink: 0;
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-size: 16px;
  color: #323233;
  margin-bottom: 6px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-meta {
  font-size: 12px;
  color: #969799;
  margin-bottom: 4px;
  display: flex;
  gap: 8px;
}

.file-path {
  font-size: 12px;
  color: #969799;
  display: flex;
  align-items: center;
  gap: 4px;
}

.file-actions {
  display: flex;
  gap: 8px;
  margin-left: 12px;
}

.empty-desc {
  text-align: center;
  color: #969799;
}

.empty-desc p {
  margin: 4px 0;
}

:deep(.van-empty) {
  padding: 80px 20px;
}

:deep(.van-notice-bar) {
  border-radius: 8px;
  margin-bottom: 8px;
}

:deep(.van-button--mini) {
  height: 28px;
  padding: 0 8px;
  font-size: 12px;
}
</style>